﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Game
{
   // 可移动物体
   class MovableObject : IGameObject
   {
      public char Name { get; set; }
      public int X { get; set; }
      public int Y { get; set; }
      public bool IsMovable { get => true; }
      // 是否为星（主人公）
      public bool IsStar { get; set; }

      // 初始化可移动物体
      public MovableObject(int x, int y, bool isStar = false)
      {
         this.X = x;
         this.Y = y;
         this.IsStar = isStar;
         this.Name = IsStar ? '*' : '$';
      }

      // 向上移动
      public void MoveUp(List<IGameObject> objects)
      {
         for (int i = X - 1; i >= 0; i--)
         {
            if (IsBlock(objects, Dirction.UP))
               break;
            else
               X = i;
         }
      }

      // 向下移动
      public void MoveDown(List<IGameObject> objects)
      {
         for (int i = X + 1; i < Core.ROW; i++)
         {
            if (IsBlock(objects, Dirction.DOWN))
               break;
            else
               X = i;
         }
      }

      // 向左移动
      public void MoveLeft(List<IGameObject> objects)
      {
         for (int i = Y - 1; i >= 0; i--)
         {
            if (IsBlock(objects, Dirction.LEFT))
               break;
            else
               Y = i;
         }
      }

      // 向右移动
      public void MoveRight(List<IGameObject> objects)
      {
         for (int i = Y + 1; i < Core.COL; i++)
         {
            if (IsBlock(objects, Dirction.RIGHT))
               break;
            else
               Y = i;
         }
      }

      // 判断移动是否被阻塞
      private bool IsBlock(List<IGameObject> objects, Dirction dir)
      {
         switch (dir)
         {
            case Dirction.LEFT:
               foreach (var item in objects)
               {
                  if (item.X == X && item.Y == Y - 1)
                     return true;
               }
               break;
            case Dirction.RIGHT:
               foreach (var item in objects)
               {
                  if (item.X == X && item.Y == Y + 1)
                     return true;
               }
               break;
            case Dirction.UP:
               foreach (var item in objects)
               {
                  if (item.Y == Y && item.X == X - 1)
                     return true;
               }
               break;
            case Dirction.DOWN:
               foreach (var item in objects)
               {
                  if (item.Y == Y && item.X == X + 1)
                     return true;
               }
               break;
            default:
               break;
         }
         return false;
      }

      // 方向
      private enum Dirction
      {
         LEFT,
         RIGHT,
         UP,
         DOWN,
      }
   }
}
